<template>
  <div>


      <ex-edit-table
      ref='exEditTable'
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading.sync="loading"
      :editRules="editRules"
      @saveRowEventEmit="saveRowEventEmit"
      @removeRowEventEmit="removeRowEventEmit"
      @editRowEventEmit="editRowEventEmit"
      >
      
      </ex-edit-table>


      <!-- 分页组件 -->
    <Pagination
      v-show="tablePage.totalResult>0"
      :total="tablePage.totalResult"
      :page.sync="tablePage.currentPage"
      :limit.sync="tablePage.pageSize"
      @pagination="pageFindList"
    />


  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'
import XEUtils,{ isNaN } from 'xe-utils'
import { filterAllRowBynormData } from '@/utils/index'
// 基础表格组件
import ExEditTable from '@/components/VxeTable/ExEditTable'
// 分页
import Pagination from '@/components/Pagination'

import {
  fetchDifferenceValue,  
  addDifferenceValue,
  updateDifferenceValue,
  deleteDifferenceValue,
  bCArithmeticMeanQueryCurveType,
  bCArithmeticMeanQueryCurve,
  bCArithmeticMeanQueryADJtype,
  bCArithmeticMeanQueryADJcp,
  bCArithmeticMeanQueryTerm
  // addBasicPrice, 
  // updateBasicPrice, 
  // deleteBasicPrice 
} from './service/baseApi'

export default {
  name: 'DiffValSetTable',
  components: {
    ExEditTable,
    Pagination
  },
  props: {
    /* 当前行数据 */
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    },
    // //期限点编号--待
    // stayTermCodeOptions: {
    //   type: Array
    // },
    // //期限点编号--叠
    // sppstTermCodeOptions: {
    //   type: Array
    // },
    // //期限点编号--合
    // mergeTermCodeOptions: {
    //   type: Array
    // },
  },
  // 定义属性
  data() {
    
    return {
      // 表单数据对象
      formSubmitData: {
        id: undefined,
        m_id: "",
        m_cv_type: "", //原曲线类型
        m_cv_code: "", //原曲线
        m_term_code: "", //原曲线期限点
        s_cv_type: "", //相减曲线类型
        s_cv_code: "", //相减曲线
        s_term_code: "", //相减曲线期限点
        adj_type: "", //调整类型
        adj_value: "", //值
        adj_cp: "", //调整单位
        // remark: "" //备注
      },

      
      /* 分页相关 */
      tablePage: {
        currentPage: 1, //当前页
        pageSize: 50,  /* TODO: 每页页数，api接口数据超过50时，需要修改此处 */
        totalResult: 0
      },

      /* 表格相关 */
      loading:false,
      tableData: [],
      tableColumn: [
        // { type: 'seq', width: 60 },
        { type: 'checkbox', width: 50 },
        { field: 'id', width: 160,title: 'ID',visible:false },
        { field: 'm_id', width: 160,title: 'MID',visible:false },
        /* 原 */
        { 
          field: 'm_cv_type', width: 160,title: '原曲线类型', 
          editRender: { 
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
            events: { change: this.mCvTypeChange }
          } 
        },
        { 
          field: 'm_cv_code', width: 160,  title: '原曲线', 
          editRender: { 
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
            events: { change: this.mCvCodeChangeEmit }
          },
          slots:{
            default: ({ row }) => {
              return [
                <span>{ row.m_cv_name }</span>
              ]
            },
          }
        },
        { 
          field: 'm_term_code', width: 160,title: '原曲线期限点', 
          editRender: { 
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
          },
          slots:{
            default: ({ row }) => {
              return [
                <span>{ row.m_term_name }</span>
              ]
            },
          }
        },
        /* 相减 */
        { 
          field: 's_cv_type', width: 160,title: '相减曲线类型', 
          editRender: { 
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
            events: { change: this.sCvTypeChange }
          }
        },
        { 
          field: 's_cv_code', width: 160,title: '相减曲线', 
          editRender: { 
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
            events: { change: this.sTermCodeChangeEmit }
          },
          slots:{
            default: ({ row }) => {
              return [
                <span>{ row.s_cv_name }</span>
              ]
            },
          }
        },
        {
          field: 's_term_code', width: 160,title: '相减曲线期限点', 
          editRender: {
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
          },
          slots:{
            default: ({ row }) => {
              return [
                <span>{ row.s_term_name }</span>
              ]
            },
          }
        },
        { 
          field: 'adj_type', width: 160,title: '调整类型', 
          editRender: {
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
          }
        },
        { 
          field: 'adj_value',width: 160, title: '值', 
          editRender: { 
            name: 'ElInputNumber',
            props: { size: 'small'},
          } 
        },
        { 
          field: 'adj_cp', width: 160,title: '调整单位', 
          editRender: {
            name: 'ElSelect', 
            options: [] ,
            props: { size: 'small', clearable: true },
          }
        },

        // { 
        //   field: 'remark', width: 160,title: '备注', 
        //   editRender: {
        //     name: 'ElInput', 
        //     options: [] ,
        //     props: { size: 'small', clearable: true ,type:'textarea',rows:1},
        //   } 
        // },

       /* jsx 书写示例 */
        //   { 
        //   field: 'm_cv_code', 
        //   width: 160,
        //   title: '原曲线', 
        //   editRender: { autofocus: '.vxe-default-select' },
        //   slots:{
        //     default: ({ row }) => {
        //       return [
        //         <span>￥{ row.m_cv_code }元</span>
        //       ]
        //     },
        //     edit: ({ row }) => {
        //       return [
        //         <vxe-select v-model={row.m_cv_code} placeholder="" onChange={ evnt => this.mCvTypeChange({evnt, row}) }>
        //           {
        //             this.bCCurveTypeOptions.map(item=>{
        //               return <vxe-option  key={item.code} value={item.code} label={item.name}></vxe-option>
        //             })
        //           }
        //        </vxe-select>
        //         // <input type="number" class="vxe-default-select" onChange={ evnt => this.mCvTypeChange({evnt, row}) } v-model={ row.m_cv_code }  />
        //       ]
        //     }
        //   }
        // },
        { title: '操作',fixed:'right', width: 200, slots: { default: 'operate' } }
      ],
      editRules:{
        m_cv_type: [
          { required: true, message: '原曲线类型,不能为空' },
        ],
        m_cv_code: [
          { required: true, message: '原曲线,不能为空' },
        ],
        m_term_code: [
          { required: true, message: '原曲线期限点,不能为空' },
        ],
        s_cv_type: [
          { required: true, message: '相减曲线类型,不能为空' },
        ],
        s_cv_code: [
          { required: true, message: '相减曲线,不能为空' },
        ],
        s_term_code: [
          { required: true, message: '相减曲线期限点,不能为空' },
        ],
        adj_type: [
          { required: true, message: '调整类型,不能为空' },
        ],
        adj_value: [
          { required: true, message: '值,不能为空' },
        ],
        adj_cp: [
          { required: true, message: '调整单位,不能为空' },
        ],
        
      }




    }
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
  },
  // 监控data中的数据变化
  watch: {
    currentRow(dataVal, oldVal){
      this.findFetchDifferenceValue()
      // 获取曲线类型
      this.getBCArithmeticMeanQueryCurveType()
      // 获取调整类型
      this.getBCArithmeticMeanQueryADJtype()
      // 获取调整单位
      this.getBCArithmeticMeanQueryADJcp()
    }
  },
  // 方法集合
  methods: {
    /**
     * 过滤表单提交之外的数据（返回新数组）
     */
    // filterFormSubmitDataExcept(obj){
    //   let f,allRow
    //   if (XEUtils.isEmpty(obj.allRow) || XEUtils.isEmpty(obj.formSubmitData)) {
    //     return []
    //   }
    //   allRow = obj.allRow
    //   f = obj.formSubmitData

    //   XEUtils.objectEach (allRow, (item, key) => {
    //     if (!f.hasOwnProperty(key)) {
    //       delete allRow[`${key}`]
    //     }
    //   })
    //   return allRow
    // },
    /* 点击编辑按钮 */
    async editRowEventEmit(row){
      
      // 重置select：options 原曲线
      await this.getBCArithmeticMeanQueryCurve(row.m_cv_type, 'y')
      // 重置select：options 相减曲线
      await this.getBCArithmeticMeanQueryCurve(row.s_cv_type, 'xj')
      // 重置select：options 原曲线期限点
      await this.findBCArithmeticMeanQueryTerm(row,'y')
      // 重置select：options 相减曲线期限点
      await this.findBCArithmeticMeanQueryTerm(row,'xj')
      // 当前行开启编辑模式
      await this.$refs.exEditTable.$refs.xGrid.setActiveRow(row)
    },
    async saveRowEventEmit(row){


        // 排除FormSubmitData没有的元素
        row = filterAllRowBynormData({
          allRow: XEUtils.clone(row, true),
          normData:this.formSubmitData
        })


      if (XEUtils.isEmpty(row.id)) {
        await addDifferenceValue({
          m_id: this.currentRow.id,
          ...row,  //检索条件
        }).then(({data}) => {
          this.findFetchDifferenceValue()
        })

      }else{
  
        await updateDifferenceValue({
          m_id: this.currentRow.id,
          ...row,  //检索条件
        }).then(({data}) => {
          this.findFetchDifferenceValue()
        })
      }
      

      // await this.findTCCurveSuperpositionFindTCCurveSuperpositionzi(this.currentRow.id)

      // await this.$emit('handleFindListEmit')

      // console.log('saveRowEventEmitsaveRowEventEmit',row);
      // console.log('removeRowEventEmitremoveRowEventEmit-mid',this.currentRow.id);
    },
    removeRowEventEmit(row){

      deleteDifferenceValue({
        id: row.id,
        // m_id: this.currentRow.id,
      }).then(({data}) => {
        this.findFetchDifferenceValue()
      })

      // deleteTCCurveSuperpositionzi({
      //   id:row.id
      // }).then(({data}) => {
      //   this.$refs.exEditTable.$refs.xGrid.remove(row)
      // })
      // console.log('removeRowEventEmitremoveRowEventEmit',row);
      // console.log('removeRowEventEmitremoveRowEventEmit-mid',this.currentRow.id);
    },


    /* API数据操作相关 */
    // 获取原曲线类型/相减曲线类型
    getBCArithmeticMeanQueryCurveType() {
      bCArithmeticMeanQueryCurveType({}).then(({data}) => {
        // // 原曲线类型
        // this.bCCurveTypeOptions = data
        // console.log('this.bCCurveTypeOptions ',this.bCCurveTypeOptions);
        // // 相减类型
        // this.sCvTypeOptions = data

        const m_cv_type_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('m_cv_type')
        m_cv_type_column.editRender.options = XEUtils.map(data, item =>{
          return {
            label:item.name,
            value:item.code
          }
        })

        const s_cv_type_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('s_cv_type')
        s_cv_type_column.editRender.options = XEUtils.map(data, item =>{
          return {
            label:item.name,
            value:item.code
          }
        })
      })
    },
     // 获取曲线
    getBCArithmeticMeanQueryCurve(val, type) {
      bCArithmeticMeanQueryCurve({
        m_cv_type: val
      }).then(({data}) => {
        if (type == 'y') {
          const m_cv_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('m_cv_code')
          m_cv_code_column.editRender.options = XEUtils.map(data, item =>{
            return {
              label:item.cv_name,
              value:item.cv_code
            }
          })

        }
        if (type == 'xj') {
          const s_cv_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('s_cv_code')
          s_cv_code_column.editRender.options = XEUtils.map(data, item =>{
            return {
              label:item.cv_name,
              value:item.cv_code
            }
          })
        }

      })
    },
    // 获取原曲线
    mCvTypeChange({row}) {
      console.log('获取原曲线',row);
      row.m_cv_code = '' //重置原曲线
      row.m_term_code = '' //重置原曲线期限点
      // 原曲线期限点selectOptions为空
      const m_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('m_term_code')
      m_term_code_column.editRender.options = []

      this.getBCArithmeticMeanQueryCurve(row.m_cv_type, 'y')
    },
    // 获取相减曲线
    sCvTypeChange({row}) {
      console.log('获取相减曲线');
      row.s_cv_code = '' //重置相减曲线
      row.s_term_code = '' //重置相减曲线期限点
      // 相减曲线期限点selectOptions为空
      const s_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('s_term_code')
      s_term_code_column.editRender.options = []
      
      this.getBCArithmeticMeanQueryCurve(row.s_cv_type, 'xj')
    },
    // 获取曲线期限点
    findBCArithmeticMeanQueryTerm(row,type){
      // 原
      if (type==='y') {
        bCArithmeticMeanQueryTerm({
          type: row.m_cv_type,
          cv_code: row.m_cv_code,
          s_date: this.currentRow.s_date,
          e_date: this.currentRow.e_date
        }).then(({data}) => {
          const m_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('m_term_code')
            m_term_code_column.editRender.options = XEUtils.map(data, item =>{
              return {
                label:item.term_name,
                value:item.term_code
              }
            })
        })
      }
      // 相减
      if (type==='xj') {
        bCArithmeticMeanQueryTerm({
          type: row.s_cv_type,
          cv_code: row.s_cv_code,
          s_date: this.currentRow.s_date,
          e_date: this.currentRow.e_date
        }).then(({data}) => {
          const s_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('s_term_code')
            s_term_code_column.editRender.options = []
            s_term_code_column.editRender.options = XEUtils.map(data, item =>{
              return {
                label:item.term_name,
                value:item.term_code
              }
            })
        })
      }
    },
    // 原曲线期限点
    mCvCodeChangeEmit({row}) {
      row.m_term_code = ''
      this.findBCArithmeticMeanQueryTerm(row,'y')
    },
    // 相减曲线期限点
    sTermCodeChangeEmit({row}) {
      row.s_term_code = ''
      this.findBCArithmeticMeanQueryTerm(row,'xj')
    },


    // 获取调整类型选项
    getBCArithmeticMeanQueryADJtype() {
      bCArithmeticMeanQueryADJtype({}).then(({data}) => {
        // this.adjTypeOptions = data
        const adj_type_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('adj_type')
          adj_type_column.editRender.options = []
          adj_type_column.editRender.options = XEUtils.map(data, item =>{
            return {
              label:item.name,
              value:item.code
            }
          })
      })
    },
    // 调整单位选项
    getBCArithmeticMeanQueryADJcp() {
      bCArithmeticMeanQueryADJcp().then(({data}) => {
        // this.adjCpOptions = data
        const adj_cp_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('adj_cp')
          adj_cp_column.editRender.options = []
          adj_cp_column.editRender.options = XEUtils.map(data, item =>{
            return {
              label:item.name,
              value:item.code
            }
          })
      })
    },


    // findTCCurveSuperpositionFindtermCode(row){
      // 待
      // tCCurveSuperpositionFindtermCode({
      //   type:row.stay_type,
      //   s_date:row.s_date,
      //   e_date:row.e_date,
      //   cv_code:row.stay_curve_code
      // }).then(({data}) => {

      //   const stay_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('stay_term_code')
      //   stay_term_code_column.editRender.options = XEUtils.map(data.rows, item =>{
      //     return {
      //       label:item.term_name,
      //       value:item.term_code
      //     }
      //   })
      //   console.log('apida333333ta.rows',data.rows);

      //   // this.stayTermCodeOptions = data.rows
    
      //   // console.log('apidata.rows',this.stayTermCodeOptions);



      // }, error => {
      //   console.log('getList:error', error);
      // })
      // // 叠
      // tCCurveSuperpositionFindtermCode({
      //   type:row.sppst_type,
      //   s_date:row.s_date,
      //   e_date:row.e_date,
      //   cv_code:row.sppst_curve_code
      // }).then(({data}) => {

      //   const merge_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('merge_term_code')
      //   merge_term_code_column.editRender.options = XEUtils.map(data.rows, item =>{
      //     return {
      //       label:item.term_name,
      //       value:item.term_code
      //     }
      //   })

      //   // this.sppstTermCodeOptions = data.rows
        



      // }, error => {
      //   console.log('getList:error', error);
      // })
      // // 合
      // tCCurveSuperpositionFindtermCode({
      //   type:row.merge_type,
      //   s_date:row.s_date,
      //   e_date:row.e_date,
      //   cv_code:row.merge_curve_code
      // }).then(({data}) => {

      //   const sppst_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('sppst_term_code')
      //   sppst_term_code_column.editRender.options = XEUtils.map(data.rows, item =>{
      //     return {
      //       label:item.term_name,
      //       value:item.term_code
      //     }
      //   })
      // }, error => {
      //   console.log('getList:error', error);
      // })

    // },

    /* 查询 */
    findFetchDifferenceValue(){

      this.loading = true

      fetchDifferenceValue({
        // page: this.tablePage.currentPage, // 当前页
        // pageSize: this.tablePage.pageSize, // 每页条数
        m_id: this.currentRow.id,
        // ...this.formSearchData,  //检索条件
      }).then(({data}) => {
        // 给表格数据赋值
        this.tableData = data.rows
        // 给分页总数赋值
        this.tablePage.totalResult = data.total
        // 关闭加载特效
        setTimeout(() => {
          this.loading = false
        }, 0.5 * 1000)
      })
    },


    pageFindList() {
      this.findFetchDifferenceValue()
    },

  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 获取列表数据
    this.findFetchDifferenceValue()

    // 获取曲线类型
    this.getBCArithmeticMeanQueryCurveType()
    // 获取调整类型
    this.getBCArithmeticMeanQueryADJtype()
    // 获取调整单位
    this.getBCArithmeticMeanQueryADJcp()

    // console.log('currentRowcurrentRow',this.currentRow);
    // this.findTCCurveSuperpositionFindTCCurveSuperpositionzi(this.currentRow.id)
    // // 获取期限字符串选项
    // this.findTCCurveSuperpositionFindtermCode(this.currentRow)

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
        console.log('columncolumncolumnco3lumn',this.$refs.exEditTable);
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
  
</style>